package com.juyu.miliao.common.dataSource.id;

import java.util.List;
import java.util.Map;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.juyu.miliao.common.dataSource.MultipleDataSourceConfig;

public class RedisIdMapper implements IdMapper{
	private final MultipleDataSourceConfig multipleDataSourceConfig;
	private final StringRedisTemplate stringRedisTemplate;

	public RedisIdMapper(MultipleDataSourceConfig multipleDataSourceConfig, StringRedisTemplate stringRedisTemplate){
		this.multipleDataSourceConfig = multipleDataSourceConfig;
		this.stringRedisTemplate = stringRedisTemplate;
	}
	
	@Override
	public String newId(String dataSourceName) {
		List<Map<String, String>> configs = multipleDataSourceConfig.getDataSource().get(dataSourceName);
		if(configs == null)
			throw new NullPointerException("数据源不存在：" + dataSourceName);
		long increment = stringRedisTemplate.opsForValue().increment(dataSourceName + ":id", 1L);
		return String.valueOf(increment * 100 + increment % 2);
	}

	@Override
	public String toDataSourceKey(String dataSourceName, String id) {
		return dataSourceName + "[" + Integer.parseInt(id)%100 + "]";
	}
	
}
